<template>
  <tl-sub-page :render="render" ref="drawerRef" :visible.sync="visible" :with-header="false" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" class="tl-drawer" :size="'95%'" @open="open" @close="close" :destroy-on-close="true">
    <div class="mpm-project-container">
      <div class="mpm-project-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpmproblemheader.png" class="logo" alt="项目问题" style="width:55px;height:55px" />
          <div class="content" :title="model.projectname">
            <p>
              <b v-if="model.id">{{ model.projectname + '-' }}</b>
              <b>项目问题</b>
            </p>
            <p class="light" v-show="model.id">
              <span>申请人：{{ model.username + '【' + model.usercode + '】' }}</span>
              <span>创建时间：{{ formatDate(model.createon) }}</span>
            </p>
          </div>
        </div>
        <div class="toolbar">
          <el-button type="danger" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="mpm-project-nav" :style="{ height: mainHeight + 'px' }">
        <ul class="nav-list">
          <template v-for="item in navList">
            <li :key="item.code" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 150px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <div class="mpm-project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="mpm-project-main-container" id="sdMainContainer">
          <div style="padding: 0 10px">
            <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit">
              <a id="project" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                项目信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="projectname">
                    <el-input v-model="model.projectname" :rows="3" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="项目级别" prop="projectlevel">
                    <el-select v-model="model.projectlevel" :disabled="true">
                      <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目经理" prop="projectmanager">
                    <el-input v-model="model.projectmanager" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="项目经理工号" prop="projectmanagercode">
                    <el-input v-model="model.projectmanagercode" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <a id="feedback" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                整改反馈
              </div>
              <!-- 审批edit -->
              <el-row>
                <el-col :span="12">
                  <el-form-item label="整改计划完成日期" prop="correctiondue" :rules="rules.validateRequire">
                    <el-date-picker v-model="model.correctiondue" type="date" placeholder="整改措施计划完成日期" value-format="yyyy-MM-dd" v-bind:disabled="!disableEdit()" :picker-options="pickerOptions"> </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="问题责任人" prop="responsible" :rules="rules.validateRequire">
                    <tl-ref-stakeholder v-model="model.responsiblecode" v-bind:disabled="!disableEdit()" @confirm="addConfirm" :initDisplayData.sync="model.responsible" fieldKey="usercode" :externalSelectedRowKeys="model.responsiblecode" title="选择风险责任人" :externalQueryParam="externalQueryParam" :isSingleSelect="true"></tl-ref-stakeholder>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="责任人工号" prop="responsiblecode" :rules="rules.validateRequire">
                    <el-input v-model="model.responsiblecode" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="反馈响应" prop="feedback" v-show="model.feedback">
                    <el-input v-model="model.feedback" type="textarea" maxlength="1000" show-word-limit :rows="3" v-bind:disabled="disableEdit()" :visible="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <a id="problem" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                问题详情
              </div>
              <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="true">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="问题日期" prop="problemdate">
                      <el-date-picker v-model="model.problemdate" type="date" placeholder="问题日期" value-format="yyyy-MM-dd" v-bind:disabled="DisablepProblem"></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="风险导入" prop="riskcode">
                      <el-input v-model="model.riskcode" :disabled="true" class="tl-ref-selector" :class="{ disabled: true }">
                        <el-button slot="append" type="primary" icon="el-icon-search" :disabled="true"></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="关联里程碑/任务" prop="relateobject">
                      <el-select v-model="model.relateobject" :disabled="disableSave" placeholder="请选择关联里程碑/任务" clearable>
                        <el-option v-for="item in codeModel.sdMilepostOrTaskList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="里程碑名称" prop="objectname" v-if="model.relateobject !== '2'">
                      <el-input v-model="model.objectname" :disabled="true" class="tl-ref-selector" :class="{ disabled: true }">
                        <el-button slot="append" type="primary" icon="el-icon-search" :disabled="true"></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="任务名称" prop="objectname" v-if="model.relateobject === '2'">
                      <el-input v-model="model.objectname" :disabled="true" class="tl-ref-selector" :class="{ disabled: true }">
                        <el-button slot="append" type="primary" icon="el-icon-search" :disabled="true"></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="问题等级" prop="problemlevel">
                      <el-select v-model="model.problemlevel" :disabled="true">
                        <el-option v-for="item in codeModel.projectProblemLevelList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="问题状态" prop="problemstatus">
                      <el-select v-model="model.problemstatus" :disabled="true">
                        <el-option v-for="item in codeModel.projectProblemStatusList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="问题描述" prop="problemdescription">
                      <el-input v-model="model.problemdescription" type="textarea" maxlength="1000" show-word-limit :rows="3" v-bind:disabled="DisablepProblem"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="24">
                    <el-form-item label="问题影响量化" prop="influencequatization">
                      <el-input v-model="model.influencequatization" type="textarea" maxlength="1000" show-word-limit :rows="3" placeholder="描述对成本、进度、范围等的量化描述" v-bind:disabled="DisablepProblem"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col>
                    <el-form-item label="整改措施" prop="correction" :rules="rules.lengthRequire">
                      <!--根据审批节点参数类型diable-->
                      <el-input v-model="model.correction" type="textarea" maxlength="1000" show-word-limit :rows="3" v-bind:disabled="DisablepProblem"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="备注" prop="description">
                      <el-input v-model="model.description" type="textarea" maxlength="1000" show-word-limit :rows="3" :disabled="true"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <a id="apply" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                申请信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="提交日期" prop="submitdate">
                    <el-date-picker v-model="model.submitdate" type="date" placeholder="提交日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属部门" prop="deptname">
                    <tl-ref-dept v-model="model.deptname" :initDisplayData.sync="model.deptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true"></tl-ref-dept>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人姓名" prop="username">
                    <tl-ref-user v-model="model.username" :initDisplayData.sync="model.username" dataType="code" :disabled="true" :singleSelect="true"></tl-ref-user>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="usercode">
                    <el-input v-model="model.usercode" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="审批流程" prop="flowid">
                    <el-select v-model="model.flowid" filterable clearable :disabled="true">
                      <el-option v-for="item in codeModel.flowidList" :key="item.id" :label="item.name" :value="parseInt(item.id)" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态" prop="state">
                    <el-select v-model="model.state" filterable clearable :disabled="true">
                      <el-option v-for="item in codeModel.stateList" :key="item.code" :label="item.name" :value="parseInt(item.code)" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="float: right; margin-top: 10px">
              <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="uiOperateState === '3'" :disabled="disableSave"> <svg-icon icon-class="save" />保存 </el-button>
              <tl-attachment ref="attachmentRef" sourceType="GpmProjectProblem" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit">
                <el-button type="primary" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()">{{ this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : '' }} [{{ this.$refs.attachmentRef ? (this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount) : 0 }}] </el-button>
              </tl-attachment>
              <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory"> <svg-icon icon-class="list" />审批历史 </el-button>
              <!-- <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval">
                <svg-icon icon-class="undo" />取消审批
              </el-button> -->
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <tl-approval-history ref="history" sourceType="GpmProjectProblem" :sourceId="model.id" />
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import approvalHistory from '@/views/mis/cboApprovalFlowIns/approvalHistory'
import tlRefStakeholder from '../gpmProjectStakeholder/refList'

/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { formatDate } from '@tapui/utils/date'

/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { approvalHistory, tlRefStakeholder },
  data() {
    return {
      moduleTitle: '项目问题',
      urlPrefix: '/sd/projectProblem/',
      url: {
        // 额外的url
        loadProject: '/sd/project/load'
      },
      // async-validate rules
      addRules: {
        lengthRequire: [{ pattern: '.{1,}', required: 'true', message: '输入内容过短或缺失必要内容', trigger: 'change' }, { whitespace: true, required: 'true', message: '输入内容不能为空格', trigger: 'change' }]
      },
      pickerOptions: {
        // disabledDate是一个函数,参数是当前选中的日期值,这个函数需要返回一个Boolean值,
        disabledDate: (time) => {
          return this.disabledDate(time)
        }
      },
      DisablepProblem: true,
      // select 默认展开item的name
      activeName: ['1', '2', '3', '4'],
      isApproval: true,
      mainHeight: 700,
      mainScrollElement: null,
      navList: [{ name: '项目信息', on: true, code: 'project' }, { name: '整改反馈', on: false, code: 'feedback' }, { name: '问题信息', on: false, code: 'problem' }, { name: '申请信息', on: false, code: 'apply' }],
      externalQueryParam: {
        qry_projectcode: '',
        qry_stakeholdercategory: '1', // 表示类别为内部人员
        qry_enabled: '1' // 表示有效人员
      },
      projectInfo: ''
    }
  },
  methods: {
    disabledDate(time) {
      // 禁用今天之前的日期选择
      let date = new Date()
      date.setHours(0, 0, 0, 0)
      // 当日期小于当天禁用选择
      return time.getTime() < date.getTime()
    },
    assignDefaultValue() {
      if (this.isAdd) {
        if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
          this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        }
      }
    },
    // 人员选择后赋值
    addConfirm(rows, keys, values) {
      this.$set(this.model, 'responsiblecode', keys)
      this.$set(this.model, 'responsible', values)
    },
    loaded() {
      // 获取项目信息
      getAction(this.url.loadProject, { id: this.model.projectid }).then((result) => {
        this.projectInfo = result.result
      })
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
      // 相关方选人组件赋值
      this.$set(this.externalQueryParam, 'qry_projectcode', this.model.projectcode)
    },
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    /** 抽屉组件必有 **/
    formatDate(date) {
      return formatDate(new Date(date), 'yyyy-MM-dd')
    },
    /** 抽屉组件必重写，主要为了执行resizeHandler方法、给mainScrollElement赋值，并添加监听事件，不要直接复制该方法 **/
    open() {
      this.model = {}
      this.resizeHandler()
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        }
        this.mainScrollElement = this.$el.querySelector('#sdMainContainer .el-scrollbar__wrap')
        this.onMainScroll()
      })
    },
    /** 点击左侧导航，抽屉组件必有 **/
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 **/
    onMainScroll() {
      const scrollFun = () => {
        const currentEl = [...this.$el.getElementsByClassName('step-position')].find((item) => item.getBoundingClientRect().y >= 0)
        const code = currentEl ? currentEl.id : ''
        this.navList.forEach((m) => (m.on = m.code === code))
      }
      this.mainScrollElement.removeEventListener('scroll', scrollFun)
      this.mainScrollElement.addEventListener('scroll', scrollFun)
    },
    // 提交审批前校验并提交更新表单信息
    doAddsync(resolve, reject) {
      this.saveLoading = true
      this.$refs.form.validate((validate) => {
        if (validate) {
          putAction(this.url.edit, this.model)
            .then((res) => {
              if (res.success) {
                // this.$tap.message(res.message, "success")
                this.queryData(this.model.id)
                this.isAdd = false
                resolve()
              } else {
                this.$tap.alert(res.message, 'warning')
                reject()
              }
              this.afterSubmit()
              this.saveLoading = false
            })
            .catch((err) => {
              this.saveLoading = false
            })
        } else {
          reject()
        }
      })
    },
    // 初步审核之后 若直接退回 则问题状态改为关闭
    doProblemStatusSync(resolve, reject) {
      this.model.problemstatus = '关闭'
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            // this.$tap.message(res.message, "success")
            this.queryData(this.model.id)
            this.isAdd = false
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    disableEdit() {
      return this.uiOperateState === '3'
    }
  },
  created() {
    // 抽屉组件必有
    window.addEventListener('resize', this.resizeHandler)
  },
  destroyed() {
    // 抽屉组件必有
    window.removeEventListener('resize', this.resizeHandler)
  }
}
</script>

<style lang="scss" scoped></style>
